using System;
using Microsoft.CSharp;
using System.Reflection;
using System.CodeDom.Compiler;
using Microsoft.Xna.Framework.Storage;

namespace SharpWind.Scripting
{
	internal class ScriptCompiler : MarshalByRefObject
	{
		private static readonly ScriptCompiler defaultCompiler = new ScriptCompiler();

		private CSharpCodeProvider codeProvider = null;

		private CompilerParameters compilerParams = null;

		private ScriptCompiler()
		{
			this.codeProvider = new CSharpCodeProvider();

			this.compilerParams = new CompilerParameters();
			this.compilerParams.GenerateExecutable = false;
			this.compilerParams.GenerateInMemory = true;
			this.compilerParams.IncludeDebugInformation = false;
			this.compilerParams.TreatWarningsAsErrors = false;
			this.compilerParams.ReferencedAssemblies.Add( "SharpWind.dll" );
			this.compilerParams.ReferencedAssemblies.Add( "Microsoft.Xna.Framework.dll" );
			this.compilerParams.ReferencedAssemblies.Add( "Microsoft.Xna.Framework.Game.dll" );
			this.compilerParams.CompilerOptions = @"/lib:" + StorageContainer.TitleLocation;
		}

		public Assembly Compile( string[] referencedAssembiles, string source )
		{
			this.compilerParams.ReferencedAssemblies.AddRange( referencedAssembiles );

			CompilerResults results = this.codeProvider.CompileAssemblyFromSource( this.compilerParams, source );
			if( results.Errors.HasErrors )
			{
				return null;
			}

			return results.CompiledAssembly;
		}

		public static ScriptCompiler DefaultCompiler
		{
			get
			{
				return defaultCompiler;
			}
		}
	}
}
